<template>
  <el-dialog
    :title="editData ? '编辑套餐' : '新增套餐'"
    :visible="visible"
    width="900px"
    custom-class="setmenu-dialog"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="套餐名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入套餐名称" />
      </el-form-item>

      <el-form-item label="上下架状态" prop="list">
        <el-switch
          v-model="formData.list"
          :active-value="1"
          :inactive-value="0"
          active-text="上架"
          inactive-text="下架"
        />
      </el-form-item>

      <el-divider content-position="left">套餐商品</el-divider>

      <div class="selected-products">
      <div
        v-for="(product, index) in formData.products"
        :key="product.id"
        class="product-item"
      >
        <div class="product-image">
          <img :src="product.img || '/default-product.png'" />
          <div class="quantity-badge">{{ product.SpSum }}</div>
        </div>
        <div class="product-details">
          <h4>{{ product.SpPid }}</h4>
          <div class="price-controls">
            <el-input-number
              v-model="product.SpMoney"
              :min="0.01"
              :precision="2"
              controls-position="right"
              size="small"
            />
            <div class="quantity-controls">
              <el-button
                size="small"
                @click="product.SpSum > 1 ? product.SpSum-- : removeProduct(index)"
              >-</el-button>
              <span>{{ product.SpSum }}</span>
              <el-button size="small" @click="product.SpSum++">+</el-button>
            </div>
          </div>
        </div>
        <el-button
          class="delete-btn"
          type="danger"
          size="small"
          circle
          @click="removeProduct(index)"
        >
          <el-icon><Delete /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="dialog-footer">
      <div class="total-price">
        套餐总价: <span class="price">¥ {{ totalPrice }}</span>
      </div>
      <el-button type="primary" @click="showProductSelector = true">
        添加商品
      </el-button>
    </div>
    </el-form>

    <template #footer>
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="submitForm(formData.name,formData.list)">确认</el-button>
    </template>

    <!-- 商品选择器 -->
    <ProductSelectorDialog
      v-model="showProductSelector"
      v-model:visible="showProductSelector"
      @select="addProducts"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect, computed } from 'vue';
import { ElMessage } from 'element-plus';
import ProductSelectorDialog from './ProductSelectorDialog.vue';
import { Add_Setmenu, Update_Setmenu } from '@/api/products';

const props = defineProps({
  visible: Boolean,
  editData: Object
});

const emit = defineEmits(['close', 'confirm']);

const formData = reactive({
  id: '',
  name: '',
  list: 0,
  products: [] as Array<{ id: string; SpPid: string; SpMoney: number; SpSum: number,img:string }>
});

const rules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  products: [{
    validator: (_, v, cb) => v.length > 0 ? cb() : cb(new Error('至少选择一个商品'))
  }]
};

const showProductSelector = ref(false);

// 修改watchEffect监听逻辑
watchEffect(() => {
  if (props.editData) {
    formData.id = props.editData.id
    formData.name = props.editData.name
    formData.list = props.editData.list
    formData.products = props.editData.products.map(p => ({
      ...p,
      name: p.name || p.SpPid // 确保名称字段存在
    }))
  } else {
    // 完整重置表单数据
    formData.id = ''
    formData.name = ''
    formData.list = 0
    formData.products = []
    showProductSelector.value = false
  }
})

const removeProduct = (index: number) => {
  formData.products.splice(index, 1);
};

const submitForm = async (name,list) => {
  // 构造符合后端要求的数据结构
  const requestData = {
    id:formData.id,
    name: formData.name,
    list: formData.list,
    products: formData.products.map(p => ({
      id: p.id,
      name:p.SpPid,
      sum: p.SpSum,
      money: p.SpMoney,
      img:p.img,
      sumMoney: p.SpMoney * p.SpSum
    }))
  }
    if(requestData.id!=""){
      const res=await Update_Setmenu(requestData.products,{
        id:requestData.id,
        name:requestData.name,
        list:requestData.list,
      });
      if(res.code===0){
        ElMessage.success('套餐修改成功')
      emit('confirm')
      emit('close')
      }
    }else{
      try {
    const res = await Add_Setmenu(requestData.products,{
      name:requestData.name,
      list:requestData.list
    })
    if (res.code === 0) {
      ElMessage.success('套餐创建成功')
      emit('confirm')
      emit('close')
    }
  } catch (error) {
    ElMessage.error('套餐创建失败')
    console.error('提交失败:', error)
  }
    }

}

// 在添加商品时初始化价格和数量
// 修改添加商品逻辑
const addProducts = (selectedProducts: Array<{ id: string; name: string; price: number;img:string }>) => {
  selectedProducts.forEach(p => {
    const existingProduct = formData.products.find(item => item.id === p.id)
    if (existingProduct) {
      existingProduct.SpSum += 1  // 已存在时数量+1
    } else {
      formData.products.push({
        ...p,
        SpMoney: p.price,
        SpSum: 1,
        SpPid: p.name,
        img:p.img
      })
    }
  })
}

// 在表格下方添加总价显示


const totalPrice = computed(() => {
  const total = formData.products.reduce((acc, cur) => {
    return acc + (cur.SpMoney || 0) * (cur.SpSum || 1);
  }, 0);
  return total.toFixed(2);
});
</script>

<style scoped>
/* 新增样式 */
.total-price {
  margin-top: 15px;
  text-align: right;
  font-size: 16px;

}
.price-number {
    color: #f56c6c;
    font-weight: bold;
    margin-left: 10px;
  }
.product-table {
  margin-bottom: 15px;
}
.add-product {
  margin-top: 10px;
  text-align: right;
}
.selected-products {
  display: grid;
  gap: 16px;
  margin-top: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background: #f8fafc;
  position: relative;
  transition: all 0.3s ease;

  &:hover {
    transform: translateX(5px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
}

.product-image {
  position: relative;
  width: 80px;
  height: 80px;
  margin-right: 16px;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
  }

  .quantity-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: #409EFF;
    color: white;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}

.product-details {
  flex: 1;

  h4 {
    margin: 0 0 8px;
    font-size: 14px;
    color: #333;
  }

  .price-controls {
    display: flex;
    gap: 16px;
    align-items: center;
  }
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;

  span {
    min-width: 30px;
    text-align: center;
  }
}

.delete-btn {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;

  .price {
    color: #f56c6c;
    font-size: 18px;
    font-weight: bold;
    margin-left: 8px;
  }
}
</style>
